package club.web51.classroom_tool.Handler;

import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Utils.MsgUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Classname GlobalExceptionHandler
 * @Description TODO
 * @Date 2020/10/28 15:18
 * @Created by HanYuHao
 */
@RestControllerAdvice
public class GlobalExceptionHandler {



    /***
    * @Description: 全局错误返回
    * @Param: [e]
    * @return: club.web51.classroom_tool.DO.typeDO.Msg
    * @Author: HanYuHao
    * @Date: 2020/10/28
    */
    @ResponseBody
    @ExceptionHandler
    public Msg Handle(Exception e){
        e.printStackTrace();
    /**
     *  优先处理Service层的异常
    */
        if(e instanceof ErrDataException){
            ErrDataException e1 = (ErrDataException) e;
            return new Msg(e1.getCode(),e1.getMessage(),null);
        }

        if(e instanceof UnknownAccountException){
            return MsgUtil.get(MsgEnum.ERROR_LOGIN_FAIL);
        }

        if(e instanceof LockedAccountException){
            return MsgUtil.get(MsgEnum.ERROR_USER_LOCKED);
        }

        if (e instanceof IncorrectCredentialsException) {
            return MsgUtil.get(MsgEnum.ERROR_NO_ROOT);
        }

        if(e instanceof AuthenticationException){
            return MsgUtil.get(MsgEnum.ERROR_USER_LOGIN_EXIST);
        }

        if(e instanceof HttpRequestMethodNotSupportedException){
            return MsgUtil.get(MsgEnum.ERROR_DATA_EXCEPT);
        }

        if(e instanceof UnauthenticatedException){
            return MsgUtil.get(MsgEnum.ERROR_NO_ALL_ROOT);
        }
        if(e instanceof UnauthorizedException){
            return MsgUtil.get(MsgEnum.ERROR_NO_ALL_ROOT);
        }

        if(e instanceof NullPointerException){
            return MsgUtil.get(MsgEnum.ERROR_DATA_EMPTY);
        }


        if(e instanceof DataIntegrityViolationException){
            return MsgUtil.get(MsgEnum.ERROR_USER_NAME_EXIST);
        }
        /**
         * 未知错误
         */

        return MsgUtil.fail();
    }
}
